package net.magicalcloud.magicalcloud.transfer;



import net.magicalcloud.magicalcloud.transfer.bean.DownloadInfo;
import net.magicalcloud.magicalcloud.transfer.bean.ThreadInfo;
import net.magicalcloud.magicalcloud.transfer.callback.OnDownload;

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import static net.magicalcloud.magicalcloud.transfer.InitThread.DEFAULT_THREAD_NUM;

/**子线程
 * Created by Pei on 2018/6/12.
 */

public class DownloadThread extends Thread {
   private ThreadInfo threadInfo;
   private DownloadInfo downloadInfo;
   private int [] mTotalFinished;

   public DownloadThread(DownloadInfo downloadInfo,ThreadInfo threadInfo,int []progress){
       this.downloadInfo=downloadInfo;
       this.threadInfo=threadInfo;
       this.mTotalFinished=progress;
   }

    @Override
    public void run() {
        URL url=null;
        int alreadydown=0; //之前已经下载的大小
        try {
            //检查是否存在还未下载完成的文件...
            String name="/sdcard/"+downloadInfo.fileId+threadInfo.id+".txt";
            File tempfile = new File(name);
            if(tempfile.exists() && tempfile.length()>0){
                FileInputStream fis = new FileInputStream(tempfile);
                byte temp[] =new byte[1024];
                int leng = fis.read(temp);
                int downlength = Integer.parseInt(new String(temp,0,leng));

                alreadydown = downlength -threadInfo.start;

              //  currentProgress += alreadydown;//发生断点之后记录下载的文件长度..

                threadInfo.start = downlength-1;
                fis.close();
            }

            url = new URL(threadInfo.url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Range", "bytes="+threadInfo.start+"-"+threadInfo.end);
            conn.setConnectTimeout(5000);

            //获取响应码..
            int status =conn.getResponseCode();

            if(status == 206){
                InputStream in = conn.getInputStream();
                RandomAccessFile raf =new RandomAccessFile(new File(downloadInfo.filePath,downloadInfo.fileName), "rwd");

                //文件开始写入..
                raf.seek(threadInfo.start);

                int len =0;
                byte[] buffer =new byte[1024];

                //已经下载的数据长度..
                int total = 0;
                //时间
                while((len = in.read(buffer))!=-1){
                    raf.write(buffer, 0, len);
                    total += len;
                    //线程已下载进度
                    threadInfo.finished=total;
                 //   System.out.println("线程"+threadInfo.id+"total:"+total);
                    //记录当前数据下载的长度...
                    RandomAccessFile file = new RandomAccessFile("/sdcard/"+downloadInfo.fileId+threadInfo.id+".txt", "rwd");
                    file.write((total+threadInfo.start+"").getBytes());
                    file.close();

                    //尝试通知下载进度
                    notifyProgress(threadInfo.id, total+alreadydown);
                }

                raf.close();
                in.close();
            }
                System.out.println("线程："+threadInfo.id+"下载完毕");
            } catch (IOException e1) {
            e1.printStackTrace();
        }
    }


    /**
     * 通知下载进度
     * @param threadId  线程id
     * @param finished  已经完成的进度
     */
    private float oldTime = System.currentTimeMillis();
    private int lastFinished=0;
    private synchronized void notifyProgress(int threadId,int finished) {




        if(threadId>=0 && threadId < mTotalFinished.length) {
            mTotalFinished[threadId] = finished;
            int nowFinished = 0;
            for(int i = 0; i<mTotalFinished.length;i++) {
                nowFinished += mTotalFinished[i];
            }

            int progress = (int) (((float) nowFinished / (float) downloadInfo.lenght) * 100);
            //秒数差
            float current=System.currentTimeMillis();
            float deltSecond=(current - oldTime)/1000f;
            //更新时间
            oldTime =current;
            //计算速度
            float speed=(float)(nowFinished-lastFinished)/1024f/deltSecond; //  kb/s
            OnDownload download = downloadInfo.onDownload;
            download.onDownloading((float) nowFinished/1024f/1024f, progress); //执行回调，更新下载进度
            lastFinished=nowFinished;
            //start 下载完成
            if(progress >= 100) {
                for(int i=0;i<DEFAULT_THREAD_NUM;i++){
                    File file = new File("/sdcard/"+downloadInfo.fileId+i+".txt");
                    file.delete();
                }
                File file = new File(downloadInfo.filePath, downloadInfo.fileName);
                download.onDownloadFinished(file);             //执行回调，
                System.out.println("下载完成");
            }
        }
    }
}
